package com.authorization.project.authorization.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.authorization.common.utils.DateUtils;
import com.authorization.common.utils.SecurityUtils;
import com.authorization.common.utils.StringUtils;
import com.authorization.framework.web.domain.AjaxResult;
import com.authorization.project.authorization.service.IMicroserviceRelationshipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.authorization.project.authorization.mapper.MicroserviceMapper;
import com.authorization.project.authorization.domain.Microservice;
import com.authorization.project.authorization.service.IMicroserviceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 微服务Service业务层处理
 * 
 * @author 李晓雷
 * @date 2020-04-24
 */
@Service
public class MicroserviceServiceImpl implements IMicroserviceService 
{
    @Autowired
    private MicroserviceMapper microserviceMapper;

    @Autowired
    private IMicroserviceRelationshipService iMicroserviceRelationshipService;

    /**
     * 查询微服务
     * 
     * @param id 微服务ID
     * @return 微服务
     */
    @Override
    public Microservice selectMicroserviceById(Long id)
    {
        Microservice microservice = microserviceMapper.selectMicroserviceById(id);

        //设置关联为服务
        microservice.setRelationIdsList(iMicroserviceRelationshipService.selectRelationIdsByMicroserviceId(id));
        return microservice;
    }

    /**
     * 查询微服务列表
     * 
     * @param microservice 微服务
     * @return 微服务
     */
    @Override
    public List<Microservice> selectMicroserviceList(Microservice microservice)
    {
        return microserviceMapper.selectMicroserviceList(microservice);
    }

    /**
     * 新增微服务
     *
     * @param microservice 微服务
     * @return 结果
     */
    public int insert(Microservice microservice)
    {
        microservice.setCreateBy(SecurityUtils.getUsername());
        microservice.setCreateTime(DateUtils.getNowDate());
        return microserviceMapper.insertMicroservice(microservice);
    }


    /**
     * 批量新增微服务
     *
     * @param microserviceList 微服务集合
     * @return 结果
     */
    public void batchInsert(List<Microservice> microserviceList)
    {
        microserviceList.forEach(microservice -> {
            microserviceMapper.insertMicroservice(microservice);
        });
    }

    /**
     * 查询产品的微服务个数
     * @param serviceName
     * @param productId
     * @return
     */
    @Override
    public int selectNumByServicenameAndProductId(String serviceName, long productId) {
        return microserviceMapper.selectNumByServicenameAndProductId(serviceName, productId);
    }

    /**
     * 删除微服务
     * @param serviceName
     * @param productId
     */
    @Override
    public void deleteMicroserviceByServicenameAndProductId(String serviceName, long productId) {
        microserviceMapper.deleteMicroserviceByServicenameAndProductId(serviceName, productId);
    }

    /**
     * 新增微服务
     * 
     * @param microservice 微服务
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMicroservice(Microservice microservice)
    {
        //1添加关联服
        int rest = this.insert(microservice);

        //2添加微服务关联表
        //TODO 添加前递归判断下级是否一级关联过)--在全都页面选择的时候判断
        if(microservice.getRelationIdsList() !=null && !microservice.getRelationIdsList().isEmpty()){
            iMicroserviceRelationshipService.bachInsertMicroserviceRelationship(microservice.getId(), microservice.getRelationIdsList());
        }

        return rest;
    }

    /**
     * 修改微服务
     * 
     * @param microservice 微服务
     * @return 结果
     */
    public int update(Microservice microservice)
    {
        microservice.setUpdateBy(SecurityUtils.getUsername());
        microservice.setUpdateTime(DateUtils.getNowDate());
        return microserviceMapper.updateMicroservice(microservice);
    }

    /**
     * 修改微服务
     *
     * @param microservice 微服务
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMicroservice(Microservice microservice)
    {
        if(microservice.getRelationIdsList() !=null && !microservice.getRelationIdsList().isEmpty()){
            //1删除微服务关联表
            iMicroserviceRelationshipService.deleteMicroserviceRelationshipByMicroserviceId(microservice.getId());

            //2添加服务关联表
            iMicroserviceRelationshipService.bachInsertMicroserviceRelationship(microservice.getId(), microservice.getRelationIdsList());
        }

        int rest = this.update(microservice);
        return rest;
    }

    /**
     * 批量删除微服务
     * 
     * @param ids 需要删除的微服务ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteMicroserviceByIds(Long[] ids)
    {
        //1 删除中间表
        for (Long id : ids) {
            iMicroserviceRelationshipService.deleteMicroserviceRelationshipByMicroserviceId(id);
        }

        //2 删除数据
        return microserviceMapper.deleteMicroserviceByIds(ids);
    }

    /**
     * 删除微服务信息
     * 
     * @param id 微服务ID
     * @return 结果
     */
    @Override
    public int deleteMicroserviceById(Long id)
    {
        return microserviceMapper.deleteMicroserviceById(id);
    }

    /**
     * 查询微服务集合通过产品主键
     * @param productId
     * @return
     */
    @Override
    public List<Microservice> productServiceList(Long productId) {
        return microserviceMapper.productServiceList(productId);
    }

    /**
     * 根据模块ID集合获取微服务名称(默认读取基本服务)
     * @param moduleArray 模块集合
     * @param productId 产品的主键
     * @return
     */
    @Override
    public String getServiceNames(List<Long> moduleArray, Long productId) {
        List<String> seviceNameList = new ArrayList<>();
        List<Microservice> microserviceList = microserviceMapper.selectMicroserviceByIdmoduleIdsArray(moduleArray);
        //1根据模块ID集合获取微服务
        if(microserviceList!=null && !microserviceList.isEmpty()){
            microserviceList.stream().forEach(microservice -> {
                seviceNameList.add(microservice.getServicename());

                List<Microservice> nodeList = new ArrayList<>();
                //递归查询下级服务名称
                getNodeServiceRecursionById(microservice.getId(), nodeList);

                if(nodeList!=null && nodeList.size() >0){
                    nodeList.stream().forEach(node ->{
                        seviceNameList.add(node.getServicename());
                    });
                }
            });
        }
        //2 默认读取产品的基本服务
        List<String> baseMicroserviceNameList = microserviceMapper.selectMicroserviceByProductId(productId);
        if(baseMicroserviceNameList!=null && baseMicroserviceNameList.size() > 0){
            seviceNameList.addAll(baseMicroserviceNameList);
        }

        return String.join(",", seviceNameList.stream().distinct().collect(Collectors.toList()));
    }

    /**
     * 验证子服务中是否已经关联
     * @param currentServiceId
     * @param newRelationId
     * @return
     */
    @Override
    public Boolean verifyAssociation(Long currentServiceId, Long newRelationId) {
        // 1递归查当前服务下所有子集
        Boolean contain = false;
        List<Long> allNodeList = new ArrayList<>();
        selAllNodeList(currentServiceId, allNodeList);

        // 2判断是否包含 newRelationId
        if(allNodeList != null && !allNodeList.isEmpty() && allNodeList.contains(newRelationId)){
            contain = true;
        }
        return contain;
    }


    /**
     * 1递归查当前服务下所有子集
     * @param currentServiceId
     * @param allNodeList
     */
    private void selAllNodeList(Long currentServiceId, List<Long> allNodeList) {
        List<Long> nodeList = iMicroserviceRelationshipService.selectRelationIdsByMicroserviceId(currentServiceId);
        if(nodeList!=null && nodeList.size() > 0){
            allNodeList.addAll(nodeList);
            nodeList.stream().forEach(nodeId ->{
                selAllNodeList(nodeId, allNodeList);
            });
        }
    }

    /**
     * 递归查询下级服务名称
     * @param id
     * @return
     */
    private void getNodeServiceRecursionById(Long id, List<Microservice> list) {
        List<Microservice> microserviceList = microserviceMapper.selectNodeList(id);
        if(microserviceList!=null && microserviceList.size() >0){
            microserviceList.stream().forEach(microservice -> {
                list.addAll(microserviceList);
                getNodeServiceRecursionById(microservice.getId(), list);
            });
        }
    }
}
